package com.patrick.open.api.core.common;

import com.patrick.open.api.core.exception.OpenTkBizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;


@Slf4j
public class OpenTkMap extends HashMap {

	public String getStr(Object key) {
		return (String) get(key);
	}

	public Double getDouble(Object key) {
		return (Double) get(key);
	}

	public Integer getInt(Object key) {
		return (Integer) get(key);
	}

	public Long getLong(Object key) {
		return (Long) get(key);
	}

	public BigDecimal getBigDecimal(Object key) {
		return (BigDecimal) get(key);
	}

	public static void copyField(OpenTkMap src, String srcName, OpenTkMap dest, String destName) {
		dest.put(destName, src.get(srcName));
	}

	/**
	 * 拷贝字段
	 *
	 * @param src      源对象
	 * @param srcName  源名称
	 * @param destName 目标名称
	 */
	public void copyField(OpenTkMap src, String srcName, String destName) {
		this.put(destName, src.get(srcName));
	}


	public <T> T toBean(Class<T> clazz) throws OpenTkBizException {
		try {
			T bean = clazz.newInstance();
			Iterator it = this.entrySet().iterator();
			while (it.hasNext()) {
				Entry entry = (Entry) it.next();
				Object key = entry.getKey();
				Object value = entry.getValue();

				Method method = null;
				if (value != null) {
					method = BeanUtils.findMethod(clazz, "set" + key, value.getClass());
				} else {
					method = BeanUtils.findMethodWithMinimalParameters(clazz, "set" + key);
				}
				if (method != null) {
					method.invoke(bean, value);
				} else {
					log.warn(String.format("未找到属性[%s]的setter方法[%s]", key, clazz.getCanonicalName()));
				}
			}
			return bean;
		} catch (IllegalAccessException e) {
			log.error(String.format("调用bean方法失败[%s]", clazz.getCanonicalName()), e);
		} catch (InvocationTargetException e) {
			log.error(String.format("调用bean方法失败[%s]", clazz.getCanonicalName()), e);
		} catch (InstantiationException e) {
			log.error(String.format("实例化bean[%s]失败", clazz.getCanonicalName()), e);
		}
		throw new OpenTkBizException(RespCode.SERVICE_DEAL_ERROR.getCode(), RespCode.SERVICE_DEAL_ERROR.getMsg());
	}
}
